package com.example.interview.common;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ChatRoom
 * @Description TODO
 * @Author mengq
 * @Date 2021/2/26 21:16
 **/
@Slf4j
public class ChatRoom {
    private ConcurrentHashMap<String, Person> persons = new ConcurrentHashMap<String, Person>();

    private String roomId;

    public ChatRoom(String roomId) {
        this.roomId = roomId;
    }

    public String add(String userId, Person person) {
        Person old = persons.get(userId);
        String res;
        if (null == old) {
            printPersons();
            //先打印再加入
            persons.put(userId, person);
            res = "userId = " + userId + " 加入roomId= " + roomId;
            log.info(res);
        } else {
            res = "userId = " + userId + " 已加入roomId= " + roomId;
        }
        return res;
    }

    public String remove(String userId, Person person) {
        //先移出再打印
        boolean result = persons.remove(userId, person);
        String res;
        if (true == result) {
            res = "userId = " + userId + " 已移出roomId= " + roomId;
            log.info(res);
            printPersons();
        } else {
            res = "userId = " + userId + " 未加入roomId= " + roomId;
        }
        return res;
    }

    private void printPersons() {
        log.info("roomId = " + roomId + "现有游客" + persons.size() + "人");
        log.info("开始打印roomId=" + roomId + "的现有成员");
        Iterator<ConcurrentHashMap.Entry<String, Person>> entries = persons.entrySet().iterator();
        while (entries.hasNext()) {
            ConcurrentHashMap.Entry<String, Person> entry = entries.next();
//            if (null != entry.getValue()) {
                log.info("roomId = " + roomId + "现有userId = " + entry.getKey() + ", person = " + entry.getValue());
//            }
        }
        log.info("结束打印roomId=" + roomId + "的现有成员");
    }
}
